﻿using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using ACSTools.RestConsumer;
using ACSTools.DataContracts;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace ACSTools.Win
{
    public partial class frmTLA : Form
    {
        #region Locals
        private class targetDevice
        {
            public targetDevice(string deviceID,
                                string serialNumber, 
                                string model, 
                                string manufacturer,
                                DateTime deviceLastInform,
                                string subscriberName,
                                string subscriberCode)
            {
                this.deviceID = deviceID;
                this.serialNumber = serialNumber;
                this.model = model;
                this.manufacturer = manufacturer;
                this.lastInform = deviceLastInform.Date;
                this.subscriberName = subscriberName;
                this.subscriberCode = subscriberCode;
            }
            public string deviceID { get; set; }
            public string serialNumber { get; set; }
            public string model { get; set; }
            public string manufacturer { get; set; }
            public DateTime lastInform { get; set; }
            public string subscriberName { get; set; }
            public string subscriberCode { get; set; }
        }
        private PrimeHomeWS phWS;
        private List<targetDevice> targetDevices;
        private Int32 selectedTarget = 0;
        public frmTLA()
        {
            InitializeComponent();
            phWS = new PrimeHomeWS();
        }
        #endregion

        #region Events
        private void frmTLA_Load(object sender, EventArgs e)
        {

        }
        private void cmdSearch_Click(object sender, EventArgs e)
        {
            lockGUI();

            // Obtener los dispositivos que tengan la misma MAC pero distinto OUI
            string query = "subscription with serialNumber: '" + txtMAC.Text + "' show deviceId as \"deviceId\" lastInform as \"lastInform\" model as \"model\" manufacturer as \"manufacturer\" fullName as \"subscriberName\" subscriberCode as \"subscriberCode\"";
            calqResult[] devicesFound = phWS.calq(query, 0);

            if (devicesFound == null)
            {
                MessageBox.Show("Device not found!", "Search Device", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else 
            {
                // Load Data
                targetDevices = new List<targetDevice>();
                foreach (calqResult deviceFound in devicesFound)
                {
                    targetDevices.Add(new targetDevice(deviceFound.fields.deviceId,
                                                       deviceFound.fields.serialNumber,
                                                       deviceFound.fields.model,
                                                       deviceFound.fields.manufacturer,
                                                       deviceFound.fields.lastInform,
                                                       deviceFound.fields.subscriberName,
                                                       deviceFound.fields.subscriberCode));
                }

                cmbModel.DataSource = targetDevices;
                // Load first device data
                loadSelectedTargetData();
                cmbModel.ValueMember = "deviceId";
                cmbModel.DisplayMember = "model";
                // Enable LAN unlock/lock command
                cmdEnable.Enabled = true;
                cmdDisable.Enabled = true;
                cmdClear.Enabled = true;
            }

            unlockGUI();
        }
        private void txtMAC_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode < Keys.A || e.KeyCode > Keys.F))
            {
                if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
                {
                    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                    {
                        if (e.KeyCode != Keys.Left && e.KeyCode != Keys.Right)
                        {
                            if (!(e.KeyCode == Keys.V && e.Modifiers == Keys.Control))
                            {
                                e.SuppressKeyPress = true;
                            }
                        }
                    }
                }
            }
        }
        private void cmdEnable_Click(object sender, EventArgs e)
        {
            runDeviceScript("EnableFullLANAccess");
        }
        private void cmdDisable_Click(object sender, EventArgs e)
        {
            runDeviceScript("DisableFullLANAccess");
        }
        private void cmdClear_Click(object sender, EventArgs e)
        {
            resetGUI();
        }
        private void cmbModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbModel.DataSource != null)
            {
                selectedTarget = cmbModel.SelectedIndex;
                loadSelectedTargetData();
            }
        }
        #endregion

        #region Private Methods
        private void lockGUI()
        {
            cmdSearch.Enabled = false;
            txtMAC.Enabled = false;
        }
        private void unlockGUI()
        {
            cmdSearch.Enabled = true;
            txtMAC.Enabled = true;
        }
        private void resetGUI()
        {
            cmdClear.Enabled = false;
            cmdSearch.Enabled = true;
            cmdEnable.Enabled = false;
            cmdDisable.Enabled = false;
            cmbModel.DataSource = null;
            txtLastInform.Text = string.Empty;
            txtSubscriber.Text = string.Empty;
            txtManufacturer.Text = string.Empty;
            txtSubscriberCode.Text = string.Empty;
            txtMAC.Text = string.Empty;
            txtMAC.Focus();
        }
        private void runDeviceScript(string scriptCode)
        {
            if (scriptCode != string.Empty && targetDevices != null)
            {
                DeviceAction deviceAction = phWS.getDevicActions(targetDevices[0].deviceID);
                DeviceAction.script deviceScript = new DeviceAction.script();
                
                deviceScript.scriptCode = scriptCode;
                deviceScript.status = "NEXT_SESSION";
                deviceScript.parameters = new List<DeviceAction.script.parameter>();
                deviceAction.solicit = true;
                deviceAction.scripts.Add(deviceScript);

                if (!(phWS.putDeviceActions(targetDevices[0].deviceID, deviceAction)))
                {
                    MessageBox.Show("Failed to execute device script!", "Updating device", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else MessageBox.Show("Execute device script successful!", "Updating device", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void loadSelectedTargetData()
        {
            
            DateTime lastInform = targetDevices[selectedTarget].lastInform;
            TimeSpan sinceLastInform = (DateTime.UtcNow - lastInform);
            string timeSinceLastInform = " "
                + ((sinceLastInform.Days != 0) ? sinceLastInform.Days.ToString() + "d " : "")
                + ((sinceLastInform.Hours != 0) ? sinceLastInform.Hours.ToString() + "h " : "")
                + ((sinceLastInform.Minutes != 0) ? sinceLastInform.Minutes.ToString() + "m " : "")
                + ((sinceLastInform.Seconds != 0) ? sinceLastInform.Seconds.ToString() + "s " : "");
            cmbModel.SelectedIndex = selectedTarget;
            txtManufacturer.Text = targetDevices[selectedTarget].manufacturer;
            txtLastInform.Text = lastInform.ToLongDateString() + " " + lastInform.ToLongTimeString() + "(" + timeSinceLastInform + ")";
            txtSubscriber.Text = targetDevices[selectedTarget].subscriberName;
            txtSubscriberCode.Text = targetDevices[selectedTarget].subscriberCode;
        }
        #endregion
    }
}
